package com.jsn.buildbase.audio

import android.annotation.SuppressLint
import android.app.MediaRouteButton
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.HandlerThread
import android.support.v4.media.MediaBrowserCompat
import android.support.v4.media.MediaMetadataCompat
import android.support.v4.media.session.MediaControllerCompat
import android.support.v4.media.session.PlaybackStateCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelProviders
import com.jsn.baselibx.MApp
import com.jsn.baselibx.ui.BaseActivity
import com.jsn.baselibx.util.showMessage
import com.jsn.baselibx.utils.Logs
import com.jsn.buildbase.App
import com.jsn.buildbase.R
import com.jsn.buildbase.databinding.ActivityAudioBinding
import com.jsn.buildbase.service.MusicService
import com.jsn.buildbase.utilities.InjectorUtil
import kotlinx.android.synthetic.main.fragment_homehaha.*


class AudioActivity:BaseActivity<ActivityAudioBinding>() {

    companion object{
        fun show(context: Context,url:String?=""){
            Intent(context,AudioActivity::class.java).apply{
                if(!url.isNullOrBlank()) putExtra("music",url)
            }.also { context.startActivity(it) }
        }
    }

    private lateinit var mMediaBrowserCompat: MediaBrowserCompat

    private val connectionCallback: MediaBrowserCompat.ConnectionCallback = object : MediaBrowserCompat.ConnectionCallback() {

        @SuppressLint("SetTextI18n")
        override fun onConnected() {
            // The browser connected to the session successfully, use the token to create the controller
            super.onConnected()
            bt.text="play"
            bt.isEnabled=true
            MApp.instance?.showMessage("conneted")
            mMediaBrowserCompat.sessionToken.also { token ->
                val mediaController = MediaControllerCompat(this@AudioActivity, token)  //get a controller using a token
                MediaControllerCompat.setMediaController(this@AudioActivity, mediaController)
            }
            playPauseBuild()
            Logs.e("onConnected", "Controller Connected")
        }

        override fun onConnectionFailed() {
            super.onConnectionFailed()
            Logs.e("onConnectionFailed", "Connection Failed")

        }

    }

    private val mControllerCallback = object : MediaControllerCompat.Callback() {
        override fun onPlaybackStateChanged(state: PlaybackStateCompat?) {
            super.onPlaybackStateChanged(state)
            MApp.instance?.showMessage("${state}")
        }

        override fun onMetadataChanged(metadata: MediaMetadataCompat?) {
            super.onMetadataChanged(metadata)
            MApp.instance?.showMessage("${metadata}")
        }

        override fun onSessionDestroyed() {
            super.onSessionDestroyed()
        }
    }

    fun playPauseBuild() {
        val mediaController = MediaControllerCompat.getMediaController(this@AudioActivity)
        bt.setOnClickListener {
            val state = mediaController.playbackState.state
            // if it is not playing then what are you waiting for ? PLAY !
            if (state == PlaybackStateCompat.STATE_PAUSED ||
                state == PlaybackStateCompat.STATE_STOPPED ||
                state == PlaybackStateCompat.STATE_NONE
            ) {
                mediaController.transportControls.playFromUri(Uri.parse("assets:///music.mp3"), null)
                bt.text = "Pause"
            }
            // you are playing ? knock it off !
            else if (state == PlaybackStateCompat.STATE_PLAYING ||
                state == PlaybackStateCompat.STATE_BUFFERING ||
                state == PlaybackStateCompat.STATE_CONNECTING
            ) {
                mediaController.transportControls.pause()
                bt.text = "Play"
            }
        }
        mediaController.registerCallback(mControllerCallback)

    }

    lateinit var viewModel: AudioViewModel

    override fun getContentView(): Int {
        return R.layout.activity_audio
    }

    override fun initUI() {
        viewModel=ViewModelProviders.of(this,InjectorUtil.provideAudioViewModelFactory())
            .get(AudioViewModel::class.java)

    }

    override fun initData() {
        val componentName=ComponentName(this,MusicService::class.java)
        mMediaBrowserCompat=MediaBrowserCompat(this,componentName,connectionCallback, null)
    }

    override fun onStart() {
        super.onStart()
       // mMediaBrowserCompat.connect()
    }

    override fun onStop() {
        super.onStop()
        // Release the resources
        val controllerCompat = MediaControllerCompat.getMediaController(this)
        controllerCompat?.unregisterCallback(mControllerCallback)
       // mMediaBrowserCompat.disconnect()
    }

    fun test(){
        HandlerThread("test").start()
        Thread("hhaha").start()
    }
}